<template>
  <div class="app-container" v-loading="loading">
    <cfCard title='' class='page-container-search bottom12'>
      <div slot='content'>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="表名称" prop="tableName">
            <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable @keyup.enter.native="handleSearch" />
          </el-form-item>
          <el-form-item label="表描述" prop="tableComment">
            <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable @keyup.enter.native="handleSearch" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </cfCard>
    <cfCard title='列表' hasTable :tableObj='tableDataObj' class='page_component-container-top'>
      <span slot="btn">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleGenTable" v-hasPermi="['tool:gen:code']" >生成</el-button>
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportTable" v-hasPermi="['tool:gen:import']" >导入</el-button>
      </span>
      <div slot='content'>
        <cfTable ref='cfTable' :tableDataObj='tableDataObj' :tableData='tableData' @handleSelectionChange="handleSelectionChange">
			    <template slot='account'>
			      <el-table-column label='账号' width='100px'>
			        <span slot-scope='{row}'>
			          {{ row.account }}
			        </span>
			      </el-table-column>
			    </template>
			    <template slot='operate'>
			      <el-table-column label='操作' width='280px' align='right'>
			        <span slot-scope='{row}'>
			          <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(row)" v-hasPermi="['tool:gen:preview']" >预览</el-button>
                <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditTable(row)" v-hasPermi="['tool:gen:edit']" >编辑</el-button>
                <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(row)" v-hasPermi="['tool:gen:remove']" >删除</el-button>
                <el-button type="text" size="small" icon="el-icon-refresh" @click="handleSynchDb(row)" v-hasPermi="['tool:gen:edit']" >同步</el-button>
                <el-button type="text" size="small" icon="el-icon-download" @click="handleGenTable(row)" v-hasPermi="['tool:gen:code']" >生成代码</el-button>
			        </span>
			      </el-table-column>
			    </template>
			  </cfTable>
        <pagination v-show="queryParams.total>0" :total="queryParams.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
    </cfCard>
    
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="key"
        >
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="import" @ok="handleSearch" />
    <inputDialog v-if="inputDialogObj.visible" :inputDialogObj="inputDialogObj" @handleResult="handleResult" />
    <cfPageDialog v-if='pageDialogObj.visible' :pageDialog='pageDialogObj'>
      <editTable v-if='pageDialogObj.visible' :pageDialogObj='pageDialogObj'></editTable>
    </cfPageDialog>
    
  </div>
</template>

<script>
import { listTable, previewTable, delTable, genCode, synchDb, batchGenCode, listDbTable, importTable } from "@/api/tool/gen";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
import editTable from './editTable';
export default {
  name: "Gen",
  components: {editTable},
  data() {
    return {
      loading: true, /** 遮罩层 */
      uniqueId: "", /** 唯一标识符 */
      ids: [], /** 选中数组 */
      tableNames: [], /** 选中表数组 */
      single: true, /** 非单个禁用 */
      multiple: true, /** 非多个禁用 */
      tableDataObj: { /** 表格配置 */
        id: 'tableId',
        showSelection: true,
        showIndex: true,
        defaultExpandAll: true,
        treeProps: {children: 'children', hasChildren: 'hasChildren'},
        option: [
          {id: 1, label: '表名称', prop: 'tableName', minWidth: 100, show: 1, needSlot: false},
          {id: 2, label: '表描述', prop: 'tableComment', minWidth: 150, show: 1, needSlot: false},
          {id: 3, label: '实体', prop: 'className', show: 1, needSlot: false},
          {id: 4, label: '创建时间', prop: 'createTime', width: 160, show: 1, needSlot: false},
          {id: 5, label: '更新时间', prop: 'updateTime', width: 160, show: 1, needSlot: false}
        ]
      },
      tableData: [], /** 表数据 */
      dateRange: "", /** 日期范围 */
      queryParams: { /** 查询参数 */
        pageNum: 1,
        pageSize: 10,
        total: 0,
        tableName: undefined,
        tableComment: undefined
      },
      preview: { /**预览参数 */
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      },
      inputDialogObj: {
        visible: false, /**弹窗显示隐藏 */
        title: '导入表', /**弹窗标题 */
        width: '638px', /**弹窗宽度 */
        tableDataObj: { /**弹窗表格配置 */
          id: 'tableName', /**表格主键标识 */
          multiple: true, /**表格多选 */
          apiFn: listDbTable, /**表格列表接口 */
          params: {}, /**表格列表接口默认参数 */
          searchArea: [/**表格搜索栏字段 */
            {
              label: '表名称', /**搜索区域名称*/
              value: 'tableName', /**搜索区域属性*/
              type: 'input', /**搜索区域类型 select：下拉， input：输入框*/
              list: '' /**type为select时必填，为下拉字典项*/
            },
            {
              label: '表描述', /**搜索区域名称*/
              value: 'tableComment', /**搜索区域属性*/
              type: 'input', /**搜索区域类型 select：下拉， input：输入框*/
              list: '' /**type为select时必填，为下拉字典项*/
            }
          ], 
          option: [ /**表格配置项 */
            {id: 1, label: '表名称',minWidth: 120, prop: 'tableName'},
            {id: 2, label: '表描述',minWidth: 140, prop: 'tableComment'},
            {id: 3, label: '创建时间',width: 160, prop: 'createTime'},
            {id: 4, label: '更新时间',width: 160, prop: 'updateTime'},
          ]
        }
      },
      pageDialogObj: { /**二级菜单页面配置文件*/
        visible: false, /**控制弹窗显示和隐藏*/
        id: '', /**数据唯一标识，用于详情和编辑*/
        title: '标题', /**二级菜单标题*/
        params: {},
        from: undefined, /**二级菜单操作对象来源Object：{id, title, componentName}*/
        componentName: '' /**二级菜单对应组件*/
      }
    };
  },
  created() {
    this.getList();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.queryParams.pageNum = Number(this.$route.query.pageNum);
      this.getList();
    }
  },
  methods: {
    async getList() { /** 查询表集合 */
      this.loading = true;
      const res = await listTable(this.addDateRange(this.queryParams, this.dateRange))
      if(res.code == 200) {
        this.tableData = res.rows;
        this.queryParams.total = res.total;
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleSearch() { /** 搜索按钮操作 */
      this.queryParams.pageNum = 1;
      this.tableData = [];
      this.queryParams.total = 0;
      this.getList();
    },
    async handleGenTable(row) {  /** 生成代码操作 */
      const tableNames = row.tableName || this.tableNames;
      if (tableNames == "") {
        this.$modal.msgError("请选择要生成的数据");
        return;
      }
      let res;
      this.loading = true;
      if(row.genType === "1") {
        res = await genCode(row.tableName);
      } else {
        res = await batchGenCode(tableNames);
      }
      if(res.data && res.status == 200) {
        this.downloadFilesFn(res);
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleSynchDb(row) {  /** 同步数据库操作 */
      const tableName = row.tableName;
      this.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(async()=> {
        this.loading = true;
        const res = await synchDb(tableName);
        if(res.code == 200) {
          this.$modal.msgSuccess("同步成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(() => {});
    },
    openImportTable() {  /** 打开导入表弹窗 */
      this.inputDialogObj.visible = true;
    },
    async handleResult(arr) { /**导入表回执 */
      let tableNames = arr.map(item => item.tableName);
      tableNames = tableNames.join(",");
      this.loading = true;
      const res = await importTable({ tables: tableNames });
      if (res.code === 200) {
        this.msgSuccess('导入成功');
        this.handleReset();
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleReset() {  /** 重置按钮操作 */
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleSearch();
    },
    handlePreview(row) {  /** 预览按钮 */
      previewTable(row.tableId).then(response => {
        this.preview.data = response.data;
        this.preview.open = true;
        this.preview.activeName = "domain.java";
      });
    },
    highlightedCode(code, key) {  /** 高亮显示 */
      const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
      var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      const result = hljs.highlight(language, code || "", true);
      return result.value || '&nbsp;';
    },
    clipboardSuccess() {  /** 复制代码成功 */
      this.$modal.msgSuccess("复制成功");
    },
    handleSelectionChange(selection) {  // 多选框选中数据
      this.ids = selection.map(item => item.tableId);
      this.tableNames = selection.map(item => item.tableName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleEditTable(row) {  /** 修改按钮操作 */
      const tableId = row.tableId || this.ids[0];
      const tableName = row.tableName || this.tableNames[0];
      const params = { pageNum: this.queryParams.pageNum };
      // this.$tab.openPage("修改[" + tableName + "]生成配置", '/tool/gen-edit/index/' + tableId, params);
      this.pageDialogObj.id = tableId;
      this.pageDialogObj.params = params;
      this.pageDialogObj.visible = true;
      this.pageDialogObj.title = `修改【${tableName}】生成配置`;
    },
    handleDelete(row) {  /** 删除按钮操作 */
      const tableIds = row.tableId || this.ids;
      this.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(async()=> {
        this.loading = true;
        const res = await delTable(tableIds);
        if(res.code == 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(() => {});
    }
  }
};
</script>
